package com.sxbbc.common.core.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.sxbbc.common.core.entity.jz.AgAgent;
import com.sxbbc.common.core.entity.jz.CAccount;
import com.sxbbc.common.core.entity.jz.CCustomer;
import com.sxbbc.common.core.entity.jz.CustomerLevelInfo;
import com.sxbbc.common.core.service.IAddressService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.enums.LoginChannelEnums;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.encrypts.pwd.Encode;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.dto.jz.CustomerTeamVo;
import com.sxbbc.common.core.enums.PayTypeEnums;
import com.sxbbc.common.core.enums.UserFreezeEnums;
import com.sxbbc.common.core.mapper.jz.CAccountMapper;
import com.sxbbc.common.core.mapper.jz.CCustomerMapper;
import com.sxbbc.common.core.service.ICCustomerService;
import com.sxbbc.common.core.service.ICustomerLevelInfoService;
import com.sxbbc.common.core.utils.BasePage;

/**
 * <p>
 * 会员信息表 服务实现类
 * </p>
 *
 * @author leehao
 * @since 2019-05-05
 */
@Service
public class CCustomerServiceImpl extends ServiceImpl<CCustomerMapper, CCustomer> implements ICCustomerService {

    private static final int RESET_PAYWORD = 1;
    private static final int RESET_PASSWORD = 2;

    @Autowired
    private ICustomerLevelInfoService customerLevelInfoService;
    @Autowired
    private CAccountMapper cAccountMapper;
    @Autowired
    private ICCustomerService icCustomerService;
    @Autowired
    private CCustomerMapper cCustomerMapper;
    @Autowired
    private IAddressService addressService;
    @Override
    public Page<CCustomer> queryCustomerList(BasePage<CCustomer> page, CCustomer customer) {
        QueryWrapper<CCustomer> wrapper = queryWrapper(customer);
        if (page.isPaging()) {
            super.page(page, wrapper);
        } else {
            List<CCustomer> list = super.list(wrapper);
            page.setRecords(list);
        }
        for (CCustomer c : page.getRecords()) {
            c.setChannelName(LoginChannelEnums.getName(c.getRegisterChannel()));
            CustomerLevelInfo levelInfo = customerLevelInfoService.getById(c.getLevelid());
            if (levelInfo != null) {
            	c.setLevelName(levelInfo.getName());
            }
            CCustomer parentCustomer = super.getById(c.getParentid());
            if (parentCustomer != null) {
            	c.setParentName(parentCustomer.getNickName());
            }
            String addrName = addressService.getAddrName(c.getProId(), c.getCityId(), c.getAreaId());
            c.setAddressEx(addrName);
            CAccount cAccount = cAccountMapper.getByCid(c.getId());
            c.setAccount(cAccount);
            // 查询直推间推数量
            CustomerTeamVo team = new CustomerTeamVo();
            team.setNowLayer(c.getLayer());
    		team.setCid(c.getId());
//    		// 普通会员
//    		team.setLevelid(1);
//    		int normalNum = baseMapper.countMyTeamNum(team);
//    		// 创业会员
//    		team.setLevelid(2);
//    		int pioneerNum = baseMapper.countMyTeamNum(team);
    		
    		team.setLevelid(null);
    		team.setRecommedLayer(1);
    		// 直推
    		int direct = baseMapper.countMyTeamNum(team);
    		// 间推
    		team.setRecommedLayer(2);
    		int indirect = baseMapper.countMyTeamNum(team);
    		c.setDirectNum(direct);
    		c.setIndirectNum(indirect);
//    		c.setNormalNum(normalNum);
//    		c.setPioneerNum(pioneerNum);
        }
        return page;
    }

    @Override
    public RestResponse handleCustomerStatus(Integer id, Integer status) {
        CCustomer customer = super.getById(id);
        if (customer == null) {
            return GetRest.getFail("该会员不存在");
        }
        customer.setStatus(status);
        boolean save = super.updateById(customer);
        if (!save) {
            throw new ThrowJsonException("操作会员状态异常");

        }
        return GetRest.getSuccess("操作成功");
    }

    @Override
    public RestResponse handleCustomerPassword(Integer id, Integer type) {
        CCustomer customer = super.getById(id);
        if (customer == null) {
            return GetRest.getFail("该会员不存在");
        }
        boolean save = false;
        switch (type) {
            case RESET_PAYWORD:
                String payWord = Encode.md5Encode(StaticUtils.DEFAULT_PASSWORD);
                customer.setPayWord(payWord);
                save = super.updateById(customer);
                break;
            case RESET_PASSWORD:
                String password = Encode.md5Encode(StaticUtils.DEFAULT_PASSWORD);
                customer.setPassWord(password);
                save = super.updateById(customer);
                break;
            default:
                break;
        }
        if (!save) {
            throw new ThrowJsonException("重置会员密码异常");
        }
        return GetRest.getSuccess("重置成功");
    }

    @Override
    public CCustomer getCustomer(CCustomer customer) {
        QueryWrapper<CCustomer> wrapper = new QueryWrapper<>();
        //根据手机号查询用户
        if (StringUtils.isNotBlank(customer.getPhone())) {
            wrapper.eq("phone", customer.getPhone());
        }
        //根据邮箱查询用户
        if (StringUtils.isNotBlank(customer.getEmail())) {
            wrapper.eq("email", customer.getEmail());
        }
        //根据登录名查询用户
        if (StringUtils.isNotBlank(customer.getLogin())) {
            wrapper.eq("login", customer.getLogin());
        }
        // 根据unionid查询用户
        if (StringUtils.isNotBlank(customer.getUnionid())) {
        	wrapper.eq("unionid", customer.getUnionid());
        }
        // 根据openid_program查询用户
        if (StringUtils.isNotBlank(customer.getOpenidProgram())) {
        	wrapper.eq("openid_program", customer.getOpenidProgram());
        }
        // 根据openid_wx查询用户
        if (StringUtils.isNotBlank(customer.getOpenidWx())) {
        	wrapper.eq("openid_wx", customer.getOpenidWx());
        }
        // 根据invite_code查询
        if (StringUtils.isNotBlank(customer.getInviteCode())) {
        	wrapper.eq("invite_code", customer.getInviteCode());
        }
        //根据三者匹配查询
        if (StringUtils.isNotBlank(customer.getLogin()) &&
                CalcuUtils.getInstance().isEquals(customer.getRegisterType(),StaticUtils.ACCOUNT_LOGIN)) {
            wrapper.or().eq("phone", customer.getLogin()).or().
                    eq("email", customer.getLogin()).or().
                    eq("login", customer.getLogin());
        }
        CCustomer one = super.getOne(wrapper);
        return one;
    }

    /**
     * 会员列表 公用查询条件
     *
     * @param customer 查询条件
     * @return com.baomidou.mybatisplus.mapper.EntityWrapper<com.sxbbc.common.core.entity.jz.CCustomer>
     * @author leehao
     */
    private QueryWrapper<CCustomer> queryWrapper(CCustomer customer) {
        QueryWrapper<CCustomer> wrapper = new QueryWrapper<CCustomer>();
        if (StringUtils.isNotBlank(customer.getNickName())) {
            wrapper.eq("nick_name", customer.getNickName());
        }
        if (StringUtils.isNotBlank(customer.getLogin())) {
            wrapper.eq("login", customer.getLogin());
        }
        if (StringUtils.isNotBlank(customer.getPhone())) {
        	wrapper.eq("phone", customer.getPhone());
        }
        if(StringUtils.isNotBlank(customer.getRealName())){
            wrapper.eq("real_name",customer.getRealName());
        }
        if (StringUtils.isNotBlank(customer.getQueryTime())) {
            String[] times = customer.getQueryTime().split("~");
            wrapper.apply(true, "date_format(createtime,'%Y-%m-%d') >= {0}", times[0].trim());
            wrapper.apply(true, "date_format(createtime,'%Y-%m-%d') <= {0}", times[1].trim());
        }
        if (customer.getLevelid() != null) {
            wrapper.eq("levelid", customer.getLevelid());
        }
        if(customer.getFlag() != null){
            if(customer.getFlag().equals(1)){
                wrapper.eq("parentid", customer.getParentid());
            }else if(customer.getFlag().equals(2)){
                QueryWrapper<CCustomer> wrapper2 = new QueryWrapper<>();
                wrapper2.eq("parentid",customer.getParentid());
                List<Integer> list = icCustomerService.list(wrapper2).stream().map(CCustomer::getId).collect(Collectors.toList());
                wrapper.in("parentid",list);
            }
        }
        return wrapper;
    }

    /**
     * 修改登录密码
     *
     * @param cid
     * @param password 加密后的新密码
     * @return
     */
    public RestResponse updateCustomerPassword(Integer cid, String password) {
        CCustomer customer = super.getById(cid);
        if (customer == null) {
            return GetRest.getFail("用户信息有误");
        }
        customer.setPassWord(password);
        boolean update = super.updateById(customer);
        if (!update) {
            throw new ThrowJsonException("重置会员密码异常");
        }
        return GetRest.getSuccess("修改密码成功");
    }

    /**
     * 修改支付密码
     *
     * @param cid
     * @param payword 加密后的新密码
     * @return
     */
    public RestResponse updateCustomerPayword(Integer cid, String payword) {
        CCustomer customer = super.getById(cid);
        if (customer == null) {
            return GetRest.getFail("用户信息有误");
        }
        customer.setPayWord(payword);
        boolean update = super.updateById(customer);
        if (!update) {
            throw new ThrowJsonException("修改会员支付密码异常");
        }
        return GetRest.getSuccess("修改支付密码成功");
    }

    /**
     * 设置用户邮箱
     *
     * @param cid
     * @param email
     * @return
     */
    public RestResponse updateCustomerEmail(Integer cid, String email) {
        CCustomer customer = super.getById(cid);
        if (customer == null) {
            return GetRest.getFail("用户信息有误");
        }
        customer.setEmail(email);
        boolean update = super.updateById(customer);
        if (!update) {
            throw new ThrowJsonException("绑定邮箱异常");
        }
        return GetRest.getSuccess("绑定邮箱成功");
    }

    /**
     * 设置手机号成功
     *
     * @param cid
     * @param phone
     * @return
     */
    public RestResponse updateCustomerPhone(Integer cid, String phone) {
        CCustomer customer = super.getById(cid);
        if (customer == null) {
            return GetRest.getFail("用户信息有误");
        }
        customer.setPhone(phone);
        boolean update = super.updateById(customer);
        if (!update) {
            throw new ThrowJsonException("绑定手机号异常");
        }
        return GetRest.getSuccess("绑定手机号成功");
    }


	@Override
	public CCustomer getByInviteCode(String inviteCode) {
		QueryWrapper<CCustomer> wrapper = new QueryWrapper<CCustomer>();
		wrapper.eq("invite_code", inviteCode);
		return super.getOne(wrapper);
	}

	@Override
	public String checkFrezeeCustomer(Integer type,Integer payType) {
		CalcuUtils calcuUtils = CalcuUtils.getInstance();
		//冻结账户
		if(UserFreezeEnums.CUSTOMER_PAY.getId() == type) {
			if(payType != null) {
		    	if(calcuUtils.isEquals(PayTypeEnums.PAY_MONEY.getId(), payType)) {
		    		return "账户余额冻结中无法使用，详情请联系客服";
		    	}else if(calcuUtils.isEquals(PayTypeEnums.PAY_POINT.getId(), payType)) {
		    		return "账户积分冻结中无法使用，详情请联系客服";
		    	}
			}
		}else if(UserFreezeEnums.CUSTOMER_CASH.getId() == type) {
			return "账户余额冻结中无法使用，详情请联系客服";
		}else if(UserFreezeEnums.CUSTOMER_POINT_TO_DONATE.getId() == type) {
			return "账户积分冻结中无法使用，详情请联系客服";
		}else if(UserFreezeEnums.CUSTOMER_SHARE_TO_MONEY.getId() == type) {
			return "账户共享值冻结中无法使用，详情请联系客服";
		}else if(UserFreezeEnums.CUSTOMER_RED.getId() == type) {
			return "账户资金冻结中无法使用，详情请联系客服";
		}else if(UserFreezeEnums.BUSINESS_CASH.getId() == type) {
			return "账户余额冻结中无法使用，详情请联系客服";
		}else if(UserFreezeEnums.CUSTOMER_OFFLINE_BUY.getId() == type) {
			return "账户余额冻结中无法使用，详情请联系客服";
		}
		return "";
	}

	@Override
	public String checkFrezeeCustomer(Integer status, Integer type, Integer payType) {
		if(null == status) {
			return "用户信息异常，请联系客服";
		}
		if(CalcuUtils.getInstance().isEquals(status, StaticUtils.STATUS_NO)) {
			return this.checkFrezeeCustomer(type, payType);
		}
		return "";
	}

	@Override
	public CCustomer getMineParent(Integer id) {
		CCustomer customer = super.getById(id);
		if(customer != null && customer.getParentid() != null) {
			return super.getById(customer.getParentid());
		}
		return null;
	}

    @Override
    public CCustomer selectNearPeople(int levelId, List<Integer> ids) {
        return cCustomerMapper.selectNearPeople(levelId,ids);
    }

    @Override
    public int selectEffectiveCustomerNum( AgAgent agAgent) {
        return cCustomerMapper.selectEffectiveCustomerNum(agAgent);
    }

    @Override
    public List<CCustomer> queryTeam(CCustomer customer) {
        return cCustomerMapper.queryTeam();
    }
}
